<?php
    /**
     * Created by PhpStorm.
     * 版权所有: 2019~2022 [ hhygyl ]
     * Date: 2019/7/10-16:19
     * Link: http://luckyadmin.luckyhhy.cn
     * FileName: Album.php
     * Keys: ctrl+alt+L/ctrl+s(代码格式化) ctrl+J(代码提示) ctrl+R(替换)ALT+INSERT(生成代码(如GET,SET方法,构造函数等) , 光标在类中才生效)
     * CTRL+ALT+O (优化导入的类和包 需要配置) SHIFT+F2(高亮错误或警告快速定位错误)
     * CTRL+SHIFT+Z(代码向前) CTRL+SHIFT+/ (块状注释) ctrl+shift+enter(智能完善代码 如if())
     **************************************************************
     *                                                            *
     *   .=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-.       *
     *    |                     ______                     |      *
     *    |                  .-"      "-.                  |      *
     *    |                 /            \                 |      *
     *    |     _          |              |          _     |      *
     *    |    ( \         |,  .-.  .-.  ,|         / )    |      *
     *    |     > "=._     | )(__/  \__)( |     _.=" <     |      *
     *    |    (_/"=._"=._ |/     /\     \| _.="_.="\_)    |      *
     *    |           "=._"(_     ^^     _)"_.="           |      *
     *    |               "=\__|IIIIII|__/="               |      *
     *    |              _.="| \IIIIII/ |"=._              |      *
     *    |    _     _.="_.="\          /"=._"=._     _    |      *
     *    |   ( \_.="_.="     `--------`     "=._"=._/ )   |      *
     *    |    > _.="                            "=._ <    |      *
     *    |   (_/                                    \_)   |      *
     *    |                                                |      *
     *    '-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-='      *
     *                                                            *
     *                    JUST FIND YOUR BUG !                    *
     **************************************************************
     */

    namespace app\admin\controller;


    use app\admin\model\AlbumImages;
    use service\UtilService;
    use think\Exception;
    use think\Request;
    use think\Session;
    use think\Validate;
    use service\CacheService;

    class Album extends SystemBase
    {

        protected $album;

        protected function _initialize()
        {
            parent::_initialize(); // TODO: Change the autogenerated stub
            $this->album = new \app\admin\model\Album();//相册模型
        }


        /**
         * @return mixed
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: index
         * @describe:图集模式
         */
        public function index()
        {
            $param = $this->request->param();
            $res   = $this->album->GetAlbumDataPage($param);

            $this->assign('data', $res->toArray());
            $this->assign('page', $res->render());
            return $this->fetch();
        }



        /**
         * @return mixed
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: listalbum
         * @describe:列表模式
         */
        public function listalbum()
        {
            if($this->request->isAjax()) {
                $param = $this->request->param();//接收参数

                return $this->album->GetDataPage($param);
            }
            return $this->fetch();
        }


        /**
         * @return mixed
         * @throws \Exception
         * @author: hhygyl <jackhhy520@qq.com>
         * @name: AddAlbum
         * @describe:添加相册
         */
        public function AddAlbum()
        {

            if($this->request->isAjax()) {
                $data = $this->request->post();
                try {
                    $validate = new Validate([['describe|token', 'require|max:200', '描述必须填写|描述最多200个字符']]);
                    if(!$validate->check($data)) {
                        $this->error($validate->getError());
                    }
                    if((int)$data['is_open']==1) { //相册需要加密
                        if(empty($data['pass'])) {
                            $this->error("请填写加密密码！");
                        }
                        if(strlen($data['pass']) < 6) {
                            $this->error("加密密码长度需大于6位数！");
                        }
                        $data['password'] = UtilService::think_encrypt($data['pass']); //密码加密
                    }

                    $res = $this->album->addEditData($data);

                    if($res['code']==1) {
                        if(!empty($data['images']) && isset($data['images'])) { //相册图片添加
                            $al_id  = $res['id'];
                            $arrimg = @explode(",", $data['images']);
                            $arr    = [];
                            foreach($arrimg as $k => $v){
                                $arr[] = ['img_url' => $v, 'album_id' => intval($al_id)];
                            }
                            $imgmodel = new AlbumImages();

                            $resd = $imgmodel->addData($arr);
                            if($resd!=false) {
                               db("album")->where("id", intval($res['id']))->setInc("nums", count($arr)); //更新相册图片数量
                            }
                            else {
                                $this->error("相册添加成功，图片添加失败");
                            }
                        }

                        if(isset($data['id'])) {
                            $this->AddLogs('编辑相册【'.$data['name'].'】信息');
                        }
                        else {
                            $this->AddLogs('添加相册【'.$data['name'].'】');
                        }
                        $this->success("操作成功");
                    }
                    else {
                        $this->error($res['msg']);
                    }

                } catch (Exception $exception) {
                    $this->error($exception->getMessage());
                }
            }

            $this->assign("navigate",model("navigate")->where("model_id",5)->select());
            return $this->fetch();
        }


        /**
         * @return mixed
         * @throws \Exception
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: AddImages
         * @describe:相册上传图片
         */
        public function AddImages()
        {
            if($this->request->isAjax()) {
                $data   = $this->request->post();

                $arrimg = @explode(",", $data['imgurl']);
                $arr    = [];
                foreach($arrimg as $k => $v){
                    $arr[] = ['img_url' => $v, 'album_id' => intval($data['id'])];
                }

                $imgmodel = new AlbumImages();
                $res      = $imgmodel->addData($arr);
                if($res!=false) {
                    db("album")->where("id", intval($data['id']))->setInc("nums", count($arr)); //更新相册图片数量

                    $this->AddLogs('添加相册ID【'.$data['id'].'】图片');

                    $this->success("添加成功");
                }
                else {
                    $this->error("添加失败");
                }

            }
            $id = $this->request->param("id/d");
            $this->assign("id", $id);

            return $this->fetch();
        }



        /**
         * @return mixed
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: hhygyl <jackhhy520@qq.com>
         * @name: EditAlbum
         * @describe:編輯相册
         */
        public function EditAlbum()
        {
            $id           = $this->request->param("id/d");//父id
            $info         = $this->album->get($id)->toArray();
            $info['tag']  = json_encode(@explode(",", $info['tags']));
            $info['pass'] = UtilService::think_decrypt($info['password']);
            $this->assign(compact("info"));
            $this->assign("navigate",model("navigate")->where("model_id",5)->select());
            return $this->fetch();
        }


        /**
         * @return mixed
         * @throws \think\exception\DbException
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: images
         * @describe:相册所有图片
         */
        public function images()
        {
            $imgmodel = new AlbumImages();
            if(!CacheService::get("images_album")) {
                //dump(1);
                $data = $imgmodel::all()->toArray();
                if(!empty($data)) {
                    foreach($data as $k => $v){
                        $data[$k]['name'] = db("album")->where("id", $v['album_id'])->value("name");
                    }
                }
                CacheService::set("images_album", $data);
            }
            else {

                $data = CacheService::get("images_album");
            }

            $request = Request::instance();
            $domain  = $request->domain();
            $this->assign("domain", $domain);
            //dump($data);
            $this->assign("data", $data);
            return $this->fetch();
        }


        /**
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: reload
         * @describe:刷新缓存
         */
        public function reload()
        {
            if($this->request->isAjax()) {
                CacheService::rm("images_album"); //清除缓存
                $this->success("刷新成功");
            }
        }



        /**
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: pass_lock
         * @describe:相册密码解锁
         */
        public function pass_lock()
        {
            if($this->request->isPost()) {
                $data = $this->request->post();

                if(empty($data['password'])) {
                    $this->error("请输入相册解锁密码");
                }

                $id   = intval($data['id']);
                $info = $this->album->get($id)->toArray();
                if(UtilService::think_decrypt($info['password'])==$data['password']) {
                    $this->success("解锁成功");
                }
                else {
                    $this->error("相册解锁密码错误");
                }

            }
        }

        /**
         * @return mixed
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: ViewImages
         * @describe:查看相册图片
         */
        public function ViewImages()
        {
            $id       = $this->request->param("id/d");
            $imgmodel = new AlbumImages();
            $res      = $imgmodel->getByAlbumId($id);
            $info     = $this->album->get($id)->toArray();
            $this->album->Hits($id); //点击量加一
            //dump($info);
            $this->assign("info", $info);
            $this->assign("data", $res);
            return $this->fetch('view_img');
        }


        /**
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: delete
         * @describe:删除相册
         */
        public function delete()
        {
            if($this->request->isAjax()) {
                $ids = $this->request->post("ids");
                try {
                    $res = $this->album->del($ids); //模型删除
                    if($res) {
                        $this->AddLogs('删除相册');

                        $this->success("删除成功");
                    }
                    else {
                        $this->error("删除失败");
                    }
                } catch (Exception $exception) {
                    $this->error($exception->getMessage());
                }
            }
        }



        /**
         * @return int
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: del
         * @describe:图片删除
         */
        public function del()
        {
            if($this->request->isPost()) {
                $id       = $this->request->post("id");
                $imgmodel = new AlbumImages();
                return $imgmodel->del($id);
            }

        }



    }